<template>
  <div class="TabTrack">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select
          v-model="query.csmType"
          placeholder="请选择"
          style="width: 170px; margin-right: 2px;"
        >
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="csmAddress" />
        </el-select>
        <el-input v-model.trim="query.csmText" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item class="merge-item" label="结款方式:" prop="payStyle">
        <el-select v-model="query.payStyle" placeholder="请选择" clearable>
          <el-option
            v-for="item in payStyleMap"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button
          v-permission="[90303, 1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div class="mb20">
      <el-button
        v-permission="[90303, 2]"
        type="primary"
        icon="el-icon-download"
        @click="exportFile"
      >导出</el-button>
    </div>

    <!-- 表格内容 -->
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
      @expand-change="handleExpandChange"
    />
    <AddSettlement ref="settlement" @refresh="search" />
    <SettlementDialog ref="SettlementDialogRef" />
    <OrderDetailDialog ref="OrderDetailDialogRef" :tree-data="treeData" @refresh="search" />
  </div>
</template>

<script>
  import AddSettlement from './components/AddSettlementDialog.vue'
  import SettlementDialog from './components/SettlementDialog.vue'
  import OrderDetailDialog from './components/OrderDetailDialog.vue'
  import {
    queryExportDomain,
    queryMonthAccountTrackTableList,
    queryMonthAccountTrackTableListDetailView,
    monthAccCsmMonthlyTrackTableExport
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import dayjs from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'tab-track',
    components: {
      AddSettlement,
      SettlementDialog,
      OrderDetailDialog
    },
    data() {
      return {
        actionColWidth: 80,
        exportDomain: '',
        treeData: [],
        rowData: {}, // 表格当前行数据
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          code: '',
          csmType: 'csmPhone',
          csmText: ''
          // payStyle: ''
        },
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        },
        detailListCols: [
          {
            prop: 'orgName',
            label: '责任机构',
            width: 250
          },
          {
            prop: 'totalReceivable',
            label: '未结账款',
            align: 'right',
            width: 100,
            render: (h, { row, $index }) => {
              return (
              <el-link
                size='mini'
                underline={false}
                onClick={() => this.openSettlementDialog(1, row)}
              >
                {row.totalReceivable || '0.00'}
              </el-link>
              )
            }
          },
          {
            prop: 'endDt',
            label: '本期账单截至日期',
            width: 170,
            render: (h, { row, $index }) => {
              return (
              <span>
                {row.caStatus !== 10 &&
                  row.endDt &&
                  dayjs(row.endDt).format('YYYY-MM-DD')}
              </span>
              )
            }
          },
          {
            prop: 'receivables',
            label: '本期应结款',
            align: 'right',
            width: 100,
            render: (h, { row, $index }) => {
              return <span>{row.receivables || '0.00'}</span>
            }
          },
          {
            prop: 'payments',
            label: '本期核销款',
            align: 'right',
            width: 100,
            render: (h, { row, $index }) => {
              return <span>{row.payments || '0.00'}</span>
            }
          },
          {
            prop: 'caStatus',
            label: '状态',
            width: 100,
            render: (h, { row, $index }) => {
              return <span>{this.caStatusText(row.caStatus)}</span>
            }
          }
        ],
        payStyleMap: [
          {
            label: '现结',
            value: 1
          },
          {
            label: '赊销',
            value: 2
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            type: 'expand',
            render: (h, { row }) => {
              return (
              <div>
                <lb-table
                  ref='lbTableDetils'
                  border
                  element-loading-text='加载中'
                  column={this.detailListCols}
                  data={row.trackList}
                  pagination={false}
                />
              </div>
              )
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 200
          },
          {
            prop: 'csmPhone',
            label: '电话',
            width: 150
          },
          {
            prop: 'totalReceivable',
            label: '未结账款',
            width: 150,
            align: 'right',
            render: (h, { row, $index }) => {
              return (
              <el-link
                size='mini'
                underline={false}
                onClick={() => this.openSettlementDialog(1, row)}
              >
                {row.totalReceivable}
              </el-link>
              )
            }
          },
          {
            prop: 'billFund',
            width: 150,
            label: '账单应结款',
            align: 'right',
            render: (h, { row, $index }) => {
              return (
              <el-link
                size='mini'
                underline={false}
                onClick={() => this.openSettlementDialog(2, row)}
              >
                {row.billFund || '0.00'}
              </el-link>
              )
            }
          },
          {
            prop: 'billSettledFund',
            label: '账单核销款',
            align: 'right',
            width: 150,
            render: (h, { row, $index }) => {
              return <span>{row.billSettledFund || '0.00'}</span>
            }
          },
          {
            prop: 'dhxCount',
            align: 'right',
            label: '待核销数',
            width: 150
          },
          {
            prop: 'dxdCount',
            align: 'right',
            label: '待销单数',
            width: 150
          },
          {
            prop: 'ybhCount',
            align: 'right',
            width: 150,
            label: '已驳回'
          },
          {
            label: '操作',
            className: 'action-col',
            width: 120,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                <el-link
                  v-permission={[90303, 3]}
                  size='mini'
                  underline={false}
                  onClick={() => this.settlement(row)}
                >
                  结款
                </el-link>
                {row.dhxCount * 1 + row.ybhCount * 1 > 0 && (
                  <el-link
                    v-permission={[90303, 4]}
                    size='mini'
                    underline={false}
                    onClick={() => this.writeOff(row)}
                  >
                    核销
                  </el-link>
                )}
                {row.dxdCount > 0 && (
                  <el-link
                  v-permission={[90303, 5]}
                    size='mini'
                    underline={false}
                    type='danger'
                    onClick={() => this.salesOrder(row, $index)}
                  >
                    销单
                  </el-link>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    created() {
      this.getTreeData()
      this.getExportDomain()
      // this.queryOptionsMap()
    },
    methods: {
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 展开当前行触发
      async handleExpandChange(row, expanded) {
        if (!row.trackList.length) {
          const params = {
            // orgSNNo: row.orgSNNo, // 所属机构id
            csmId: row.csmId // 客户id
          }
          const { status, data } = await queryMonthAccountTrackTableListDetailView(params)
          if (status === 200) {
            row.trackList = data.trackList
          }
        }
      },
      caStatusText(val) {
        switch (val) {
        case 10:
          return '待结款'
        case 20:
          return '待核销'
        case 30:
          return '待销单'
        case 40:
          return '驳回'
        }
      },

      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.csmText) query[this.query.csmType] = this.query.csmText
        const res = await queryMonthAccountTrackTableList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows.map((v) => {
          return {
            trackList: [],
            ...v
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },

      // 结款
      settlement(row) {
        this.$refs.settlement.open(row)
        // this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打开未结款项列表
      openSettlementDialog(type, row) {
        row.orgSNNo = this.query.orgSNNo
        this.$refs['SettlementDialogRef'].show(type, row)
      },

      // 核销
      writeOff(row) {
        this.$refs['OrderDetailDialogRef'].show(1, row)
      },

      // 销单
      salesOrder(row) {
        this.$refs['OrderDetailDialogRef'].show(2, row)
      },

      del(row, index) {
        this.$confirm('确定删除此条数据？', '提示', {
          type: 'warning'
        }).then(() => {})
      },

      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          copyColumn.shift()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          monthAccCsmMonthlyTrackTableExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
.TabTrack {
  .el-form-item .el-form-item {
    margin-bottom: 0;
  }
  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
}
</style>
